package com.czk.inputstream;

import org.junit.Test;

import java.io.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/6/3 14:26
 */
public class InputStreamToStringTest {
    /**
     * 使用字符流
     */
    @Test
    public void fun_1() {
        try {
            // 拿到输入流
            InputStream inputStream = new FileInputStream("D:\\简历\\2.txt");
            // 创建缓冲区
            // 字符缓冲区
            char[] buffer = new char[1024];
            // 创建builder
            StringBuilder builder = new StringBuilder();
            // 字节流
            Reader reader = new InputStreamReader(inputStream);
            for (int len; (len = reader.read(buffer)) > 0; ) {
                System.out.println(buffer.length);
                builder.append(buffer, 0, len);
                System.out.println(buffer.length);
            }
            String string = builder.toString();
            System.out.println(string);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 使用字节流读取
     */
    @Test
    public void fun_2() {
        try {
            // 拿到输入流
            InputStream inputStream = new FileInputStream("D:\\简历\\2.txt");
            // 创建builder
            StringBuilder builder = new StringBuilder();
            // 直接读取
            for (int len; (len = inputStream.read()) != -1; ) {
                // 直接添加
                builder.append((char) len);
            }
            String string = builder.toString();
            System.out.println(string);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 利用流失api来获取
     *
     * @throws FileNotFoundException
     */
    @Test
    public void fun_3() throws FileNotFoundException {
        //
        // 拿到输入流
        InputStream inputStream = new FileInputStream("D:\\简历\\罗琴.doc");
        // 转为流
        Stream<String> lines = new BufferedReader(new InputStreamReader(inputStream)).lines();
        // 转为
        String collect = lines.parallel().collect(Collectors.joining(""));
        // 输出
        System.out.println(collect);
    }
    @Test
    public void fun_4() throws IOException {
        // 拿到输入流
        InputStream inputStream = new FileInputStream("D:\\简历\\陈彰坤-重庆理工大学.doc");
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] b = new byte[1024];
        int len = 0;
        while ((len = inputStream.read(b)) != -1) {
            byteArrayOutputStream.write(b);
        }
        String string = byteArrayOutputStream.toString("UTF-8");
        System.out.println(string);

    }
}
